<template>
  <Page class="course-mgr h-full">
    <div class="course-mgr-container flex flex-col h-full rounded-lg">
      <!-- 过滤查询组件 -->
      <CourseFilter @search="handleSearch" @reset="handleReset" @add="handleAdd" />
      <!-- 表格组件 -->
      <CourseTable class="min-h-[1px] flex-1 bg-[#fff] overflow-auto px-4 pb-4 pt-0" :table-data="tableData"
        :loading="loading" @edit="handleEdit" @delete="handleDelete" @toggle-status="handleToggleStatus" />
      <!-- 分页组件 -->
      <Pagination v-model="paginationData" :total="total" />
    </div>

    <!-- 抽屉弹窗组件 -->
    <CourseDrawer v-model="drawerVisible" :mode="drawerMode" :data="currentCourseData" @confirm="handleDrawerConfirm"
      @save-draft="handleDrawerSaveDraft" @cancel="handleDrawerCancel" @update:data="handleDrawerUpdateData" />
  </Page>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Page } from '@vben/common-ui'
import CourseFilter from './modules/course-mgr/course-filter.vue'
import CourseTable from './modules/course-mgr/course-table.vue'
import CourseDrawer from './modules/course-mgr/course-drawer.vue'
import Pagination from '#/components/pagination.vue'
import type { CourseItem, FilterForm } from './modules/course-mgr/types'
import { SvgFailIcon, SvgTipIcon, SvgSuccessIcon } from '@vben/icons'
import { getCourseInfoApi, deleteCourseInfoApi, listedCourseInfoApi, unlistedCourseInfoApi } from '#/api/manage/course'
import { $t } from '@vben/locales'
import { useMessageBox } from '#/hooks/useMessageBox'

const { confirm } = useMessageBox({})

// 响应式数据
const loading = ref(false)
const total = ref(0)
const tableData = ref<CourseItem[]>([])
const filterParams = reactive<FilterForm>({
  name: null,
  status: null,
  // subjectCategory: ''
})

// 分页数据，匹配现有 pagination 组件的 API
const paginationData = reactive({
  curPage: 1,
  pageSize: 10
})

// 抽屉弹窗相关数据
const drawerVisible = ref(false)
const drawerMode = ref<'add' | 'edit'>('add')
const currentCourseData = ref<CourseItem | undefined>()

const getCourseInfo = async () => {
  try {
    loading.value = true
    console.log('filterParams', { ...filterParams, name: filterParams.name?.trim(), ...paginationData })
    const res = await getCourseInfoApi({ ...filterParams, name: filterParams.name?.trim(), ...paginationData })
    tableData.value = res.data
    total.value = res.pageInfo.totalRows
  } catch (error) {
    ElMessage.error($t('courseMgr.getCourseListError'))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getCourseInfo()
})
// 搜索处理
const handleSearch = (form: FilterForm) => {
  Object.assign(filterParams, form)
  paginationData.curPage = 1
  getCourseInfo()
}

// 重置处理
const handleReset = () => {
  Object.assign(filterParams, {
    name: '',
    status: '',
    // subjectCategory: ''
  })
  tableData.value = []
  total.value = 0
  paginationData.curPage = 1
  getCourseInfo()
}

// 新增处理
const handleAdd = () => {
  drawerMode.value = 'add'
  currentCourseData.value = {}
  drawerVisible.value = true
}

// 编辑处理
const handleEdit = (row: CourseItem) => {
  drawerMode.value = 'edit'
  currentCourseData.value = { ...row }
  drawerVisible.value = true
}

// 删除处理
const handleDelete = async (row: CourseItem) => {
  try {
    // await ElMessageBox.confirm(
    //   $t('courseMgr.deleteConfirmMessage'),
    //   '',
    //   {
    //     icon: SvgFailIcon,
    //     confirmButtonText: $t('common.submitTxt', ['']),
    //     cancelButtonText: $t('common.cancelTxt'),
    //     type: 'warning',
    //   }
    // )
    await confirm($t('courseMgr.deleteConfirmMessage'), {})
    await deleteCourseInfoApi(row.id as number)
    ElMessage.success($t('common.deleteSuccessTxt'))
    getCourseInfo()
  } catch {
    ElMessage.info($t('common.deleteCancelledTxt'))
  }
}

// 状态切换处理
const handleToggleStatus = async ({ row, newStatus, api, message }: {
  row: CourseItem
  newStatus: 'listed' | 'unlisted'
  api: typeof listedCourseInfoApi | typeof unlistedCourseInfoApi
  message: string
}) => {
  try {
    // await ElMessageBox.confirm(
    //   message,
    //   '',
    //   {
    //     icon: SvgTipIcon,
    //     confirmButtonText: $t('common.submitTxt', ['']),
    //     cancelButtonText: $t('common.cancelTxt'),
    //     type: 'warning',
    //   }
    // )
    await confirm(message, {}, newStatus === 'listed' ? 'success' : 'fail')
    await api(row.id as number)
    const statusText = newStatus === 'listed' ? $t('courseMgr.listedSuccess') : $t('courseMgr.unlistedSuccess')
    ElMessage.success(`${row.name} ${statusText}`)
    getCourseInfo()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error($t('common.operationFailedTxt'))
    }
  }
}

// 抽屉弹窗事件处理
const handleDrawerConfirm = async (data?: CourseItem) => {
  console.log('handleDrawerConfirm', data)
  if (drawerMode.value === 'add') {

    // const res = await createCourseInfoApi(data as any)
    // console.log('res', res)
    ElMessage.success($t('courseMgr.addCourseSuccess'))
  } else {
    ElMessage.success($t('courseMgr.editCourseSuccess'))
  }
  getCourseInfo()
}

const handleDrawerSaveDraft = (data?: CourseItem) => {
  ElMessage.success($t('courseMgr.saveDraftSuccess'))
}

const handleDrawerCancel = () => {
  // 可以在这里添加取消逻辑，如提示用户是否保存等
}

const handleDrawerUpdateData = (data: CourseItem) => {
  currentCourseData.value = data
}

// 监听分页数据变化
watch(
  () => [paginationData.curPage, paginationData.pageSize],
  () => {
    getCourseInfo()
  }
)

</script>

<style scoped>
.course-mgr-container {
  min-height: 100%;
}
</style>
